package org.budo.beetl.tag.defer.write;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.beetl.core.BodyContent;
import org.beetl.core.ByteWriter;
import org.beetl.core.Tag;
import org.beetl.core.statement.BlockStatement;
import org.beetl.core.statement.Statement;
import org.budo.support.lang.util.ArrayUtil;
import org.budo.support.mvcs.Mvcs;

/**
 * @author limingwei
 */
public class DeferWriteTag extends Tag {
    private static final String REQUEST_ATTRIBUTE_KEY = "defer-write";

    @Override
    public void render() {
        BlockStatement blockStatement = (BlockStatement) this.bs;
        Statement[] nodes = blockStatement.nodes;

        if (!ArrayUtil.isEmpty(nodes)) {
            this.defer(this.getBodyContent());
        } else {
            this.write(ctx.byteWriter);
        }
    }

    protected void defer(BodyContent bodyContent) {
        List<String> list = (List<String>) Mvcs.getRequestAttribute(REQUEST_ATTRIBUTE_KEY);
        if (null == list) {
            list = new ArrayList<String>();
            Mvcs.setRequestAttribute(REQUEST_ATTRIBUTE_KEY, list);
        }
        list.add(bodyContent.getBody());
    }

    protected void write(ByteWriter byteWriter) {
        List<String> list = (List<String>) Mvcs.getRequestAttribute(REQUEST_ATTRIBUTE_KEY);
        if (null != list) {
            for (String each : list) {
                this.writeString(byteWriter, "\n");
                this.writeString(byteWriter, each);
                this.writeString(byteWriter, "\n");
            }
        }
    }

    private void writeString(ByteWriter byteWriter, String each) {
        try {
            byteWriter.writeString(each);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}